from rest_framework import serializers
from ..utils.related_util.choice_util import get_value_from_map
from ..models.unitSetModel import *
from ..utils.related_util.content_util import get_unit_set_by_unitset, get_unit_set_by_unitset_text


class UnitSetListQuerySerializer(serializers.Serializer):
    unit_set_name = serializers.CharField(required=False, allow_blank=True)
    page_size = serializers.IntegerField(
        required=False, max_value=50, min_value=1)
    current_page = serializers.IntegerField(required=False)
    sort_prop = serializers.CharField(required=False, allow_blank=True)
    sort_order = serializers.CharField(required=False, allow_blank=True)

    def validate(self, attrs):
        filter_flag = True
        page_flag = True
        if "unit_set_name" in attrs:
            attrs["unit_set_name"] = attrs["unit_set_name"].strip()
            if attrs["unit_set_name"] == "":
                attrs.pop("unit_set_name")
        if ("unit_set_name" not in attrs or attrs["unit_set_name"] == ""):
            filter_flag = False
        if ("page_size" not in attrs):
            page_flag = False
        if not filter_flag and not page_flag:
            raise serializers.ValidationError({
                'detail': '查询条件过于宽泛'
            })
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs

    @classmethod
    def get_query_fields(self):
        return [{"title": "单位制名称：", "dataIndex": "unit_set_name", "type": "CharField"}]


class UnitSetListSerializer(serializers.ModelSerializer):
    origin_unit_set = serializers.SerializerMethodField()
    is_system = serializers.SerializerMethodField()
    unit_set_name = serializers.SerializerMethodField()

    class Meta:
        model = UnitSet
        fields = ['uuid', 'unit_set_name', 'origin_unit_set',
                  'is_system', 'unit_set_description', 'unit_set_comment']

    def get_unit_set_name(self, obj):
        return obj.show_full_name()

    def get_origin_unit_set(self, obj):
        if obj.origin_unit_set == None:
            return ""
        return obj.origin_unit_set.show_short_name()

    def get_is_system(self, obj):
        bool_map = {True: "是", False: "否"}
        return get_value_from_map(obj.is_system, bool_map)

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "单位制名称", "dataIndex": "unit_set_name", "type": "CharField"}]


class UnitSetCreateSerializer(serializers.ModelSerializer):
    origin_unit_set = serializers.JSONField()
    unitsetcontent = serializers.JSONField()

    class Meta:
        model = UnitSet
        fields = ['unit_set_name', 'unit_set_name_en', 'origin_unit_set', 'is_system',
                  'unit_set_description', 'unit_set_description_en', 'unit_set_comment', 'unitsetcontent']

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data

    def validate(self, attrs):
        if "origin_unit_set" in attrs:
            if len(attrs["origin_unit_set"]) == 0:
                attrs.pop("origin_unit_set")
            else:
                attrs["origin_unit_set"] = attrs["origin_unit_set"][0]
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "单位制内容", "dataIndex": "unitsetcontent", "type": "JSONField"}]


class UnitSetInfoModifySerializer(serializers.ModelSerializer):
    origin_unit_set = serializers.SerializerMethodField()
    unitsetcontent = serializers.SerializerMethodField()

    class Meta:
        model = UnitSet
        fields = ['unit_set_name', 'unit_set_name_en', 'origin_unit_set', 'is_system',
                  'unit_set_description', 'unit_set_description_en', 'unit_set_comment', 'unitsetcontent']

    def get_origin_unit_set(self, obj):
        if obj.origin_unit_set == None:
            return []
        return [str(obj.origin_unit_set.uuid)]

    def get_unitsetcontent(self, obj):
        return get_unit_set_by_unitset(obj)

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "单位制内容", "dataIndex": "unitsetcontent", "type": "JSONField"}]


class UnitSetInfoModifyInSerializer(serializers.ModelSerializer):
    origin_unit_set = serializers.JSONField()
    unitsetcontent = serializers.JSONField()

    class Meta:
        model = UnitSet
        fields = ['unit_set_name', 'unit_set_name_en', 'origin_unit_set', 'is_system',
                  'unit_set_description', 'unit_set_description_en', 'unit_set_comment', 'unitsetcontent']

    def to_internal_value(self, data):
        data = super().to_internal_value(data)
        for field_name in self.fields:
            value = data.get(field_name)
            if isinstance(value, str):
                data[field_name] = value.strip()

        return data

    def validate(self, attrs):
        if "origin_unit_set" in attrs:
            if len(attrs["origin_unit_set"]) == 0:
                attrs.pop("origin_unit_set")
            else:
                attrs["origin_unit_set"] = attrs["origin_unit_set"][0]
        try:
            attrs = super().validate(attrs)
        except serializers.ValidationError as e:
            raise serializers.ValidationError({
                'detail': '验证失败:' + str(e.detail)
            })
        return attrs

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "单位制内容", "dataIndex": "unitsetcontent", "type": "JSONField"}]


class UnitSetInfoSerializer(serializers.ModelSerializer):
    origin_unit_set = serializers.SerializerMethodField()
    is_system = serializers.SerializerMethodField()
    unitsetcontent = serializers.SerializerMethodField()
    create_person = serializers.SerializerMethodField()
    modify_person = serializers.SerializerMethodField()

    class Meta:
        model = UnitSet
        fields = ['unit_set_name', 'unit_set_name_en', 'origin_unit_set', 'is_system',
                  'unit_set_description', 'unit_set_description_en', 'unit_set_comment', 'unitsetcontent', 'create_person', 'create_date', 'modify_person', 'modify_date']

    def get_origin_unit_set(self, obj):
        if obj.origin_unit_set == None:
            return ""
        return obj.origin_unit_set.show_short_name()

    def get_is_system(self, obj):
        bool_map = {True: "是", False: "否"}
        return get_value_from_map(obj.is_system, bool_map)

    def get_unitsetcontent(self, obj):
        return get_unit_set_by_unitset_text(obj)

    def get_create_person(self, obj):
        return obj.create_person.user_name

    def get_modify_person(self, obj):
        return obj.modify_person.user_name

    @classmethod
    def get_extra_fields_info(self):
        return [{"title": "单位制内容", "dataIndex": "unitsetcontent", "type": "JSONField"}]
